package fr.cephb.joperon.unit;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import junit.framework.JUnit4TestAdapter;
import static org.junit.Assert.*;
import org.junit.Test;

import com.sleepycat.db.DatabaseException;

import fr.cephb.berkeley.ByteReader;
import fr.cephb.berkeley.ByteWriter;
import fr.cephb.lang.Endian;
import fr.cephb.lang.UInt32;

public class TestDataTypes
	{
	@Test
	public void testInt32_1() throws IOException,DatabaseException
		{
		Integer int32a= new Integer(106649392);
		ByteWriter w= new ByteWriter();
		w.writeInt32(int32a);
		byte array1[]=w.getBytes();
		
		ByteReader r= new ByteReader(array1);
		Integer int32b= new Integer(r.readInt32());
		System.err.println(int32a+" "+int32b);
		assertTrue(int32a.equals(int32b));
		}
	
	
	@Test
	public void testUInt32_1() throws IOException,DatabaseException
		{
		UInt32 uint32a= new UInt32(101253120);
		ByteWriter w= new ByteWriter();
		w.writeUInt32(uint32a);
		byte array1[]=w.getBytes();
		
		ByteReader r= new ByteReader(array1);
		UInt32 unInt32b= new UInt32(r.readUInt32());
		assertTrue(uint32a.equals(unInt32b));
		}
	
	@Test
	public void testInt32_2() throws IOException,DatabaseException
		{
		InputStream in=TestDataTypes.class.getResourceAsStream("int32.bin");
		assertTrue(in!=null);
		byte array[]=new byte[4];
		int len;
		while((len=in.read(array))!=-1)
			{
			assertTrue(len==4);
			ByteReader r= new ByteReader(array);
			int n =r.readInt32();
			System.err.println("read int32= "+n);
			ByteWriter w= new ByteWriter();
			w.writeInt32(n);
			byte array2[]=w.getBytes();
			assertTrue(Arrays.equals(array, array2));
			}
		in.close();
		}
	
	@Test
	public void testUInt32_2() throws IOException,DatabaseException
		{
		InputStream in=TestDataTypes.class.getResourceAsStream("uint32.bin");
		assertTrue(in!=null);
		byte array[]=new byte[4];
		int len;
		while((len=in.read(array))!=-1)
			{
			assertTrue(len==4);
			ByteReader r= new ByteReader(array);
			long n =r.readUInt32();
			UInt32 uint32= new UInt32(n);
			ByteWriter w= new ByteWriter();
			w.writeUInt32(uint32);
			byte array2[]=w.getBytes();
			assertTrue(Arrays.equals(array, array2));
			}
		in.close();
		}
	
	
	public static junit.framework.Test suite() { 
	    return new JUnit4TestAdapter(TestDataTypes.class); 
	}
	
	public static void main(String[] args)
			{
			try{
			Endian.setDefault(Endian.CNG);
			org.junit.runner.JUnitCore.main(TestDataTypes.class.getName()); 
			System.out.println("OK");
			} catch(Throwable err)
			{
				err.printStackTrace();
			}
			}
	}
